/**
 * 网络请求拦截器 - 弹窗脚本
 * 负责处理插件弹窗的所有交互逻辑
 */

class NetworkInterceptorPopup {
  constructor() {
    this.currentTab = 'whitelist';
    this.currentMockId = null;
    this.requestList = [];
    this.mockList = [];
    this.webList = [];
    this.isEnabled = true;
    this.debuggerStatus = {
      enabled: false,
      attachedTabs: [],
      pendingRequests: 0
    };
    
    this.init();
  }

  /**
   * 初始化插件弹窗
   */
  async init() {
    this.bindEvents();
    await this.loadData();
    await this.refreshDebuggerStatus();
    this.updateUI();
  }

  /**
   * 绑定事件监听器
   */
  bindEvents() {
    // 标签页切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        if (e.target.id === 'open-config-btn') {
          this.openConfigPage();
        } else {
          this.switchTab(e.target.dataset.tab);
        }
      });
    });

    // 插件开关
    document.getElementById('toggle-btn').addEventListener('click', () => {
      this.togglePlugin();
    });

    // 域名白名单相关
    document.getElementById('add-domain-btn').addEventListener('click', () => {
      this.addDomain();
    });
    
    document.getElementById('domain-input').addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        this.addDomain();
      }
    });

    // 请求列表相关
    document.getElementById('clear-requests-btn').addEventListener('click', () => {
      this.clearRequests();
    });
    
    document.getElementById('refresh-requests-btn').addEventListener('click', () => {
      this.refreshRequests();
    });
    
    document.getElementById('request-filter').addEventListener('input', () => {
      this.filterRequests();
    });
    
    document.getElementById('method-filter').addEventListener('change', () => {
      this.filterRequests();
    });

    // Mock管理相关
    document.getElementById('add-mock-btn').addEventListener('click', () => {
      this.showMockModal();
    });
    
    document.getElementById('save-mock-btn').addEventListener('click', () => {
      this.saveMock();
    });
    
    document.getElementById('cancel-mock-btn').addEventListener('click', () => {
      this.hideMockModal();
    });
    
    document.getElementById('close-modal').addEventListener('click', () => {
      this.hideMockModal();
    });

    // 请求详情弹窗
    document.getElementById('close-request-modal').addEventListener('click', () => {
      this.hideRequestModal();
    });
    
    document.getElementById('close-request-details').addEventListener('click', () => {
      this.hideRequestModal();
    });
    
    document.getElementById('create-mock-from-request').addEventListener('click', () => {
      this.createMockFromRequest();
    });

    // 弹窗背景点击关闭
    document.getElementById('mock-modal').addEventListener('click', (e) => {
      if (e.target.id === 'mock-modal') {
        this.hideMockModal();
      }
    });
    
    document.getElementById('request-modal').addEventListener('click', (e) => {
      if (e.target.id === 'request-modal') {
        this.hideRequestModal();
      }
    });

    // 配置管理按钮
    document.getElementById('open-config-btn').addEventListener('click', () => {
      this.openConfigPage();
    });

    // Debugger控制按钮
    document.getElementById('debugger-toggle-btn').addEventListener('click', () => {
      this.toggleDebugger();
    });
    
    document.getElementById('debugger-status-btn').addEventListener('click', () => {
      this.refreshDebuggerStatus();
    });
  }

  /**
   * 从存储中加载数据
   */
  async loadData() {
    try {
      const result = await chrome.storage.local.get([
        'webList', 'requestList', 'mockList', 'isEnabled'
      ]);
      
      this.webList = result.webList || [];
      this.requestList = result.requestList || [];
      this.mockList = result.mockList || [];
      this.isEnabled = result.isEnabled !== false;
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  }

  /**
   * 保存数据到存储
   */
  async saveData() {
    try {
      await chrome.storage.local.set({
        webList: this.webList,
        requestList: this.requestList,
        mockList: this.mockList,
        isEnabled: this.isEnabled
      });
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  }

  /**
   * 切换标签页
   */
  switchTab(tabName) {
    // 更新标签按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

    // 更新标签页内容
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.remove('active');
    });
    document.getElementById(`${tabName}-tab`).classList.add('active');

    this.currentTab = tabName;
    this.updateTabContent();
  }

  /**
   * 更新当前标签页内容
   */
  updateTabContent() {
    switch (this.currentTab) {
      case 'whitelist':
        this.renderDomainList();
        break;
      case 'requests':
        this.renderRequestList();
        break;
      case 'mocks':
        this.renderMockList();
        break;
    }
  }

  /**
   * 更新UI状态
   */
  updateUI() {
    // 更新插件状态
    const statusText = document.getElementById('status-text');
    const toggleBtn = document.getElementById('toggle-btn');
    
    if (this.isEnabled) {
      statusText.textContent = '已启用';
      toggleBtn.textContent = '关闭';
      toggleBtn.classList.add('active');
    } else {
      statusText.textContent = '已禁用';
      toggleBtn.textContent = '开启';
      toggleBtn.classList.remove('active');
    }

    // 更新计数
    document.getElementById('domain-count').textContent = this.webList.length;
    document.getElementById('request-count').textContent = this.requestList.length;
    document.getElementById('mock-count').textContent = this.mockList.length;

    this.updateTabContent();
  }

  /**
   * 切换插件开关状态
   */
  async togglePlugin() {
    this.isEnabled = !this.isEnabled;
    await this.saveData();
    
    // 通知后台脚本状态变化
    chrome.runtime.sendMessage({
      type: 'TOGGLE_PLUGIN',
      enabled: this.isEnabled
    });
    
    this.updateUI();
  }

  /**
   * 添加域名到白名单
   */
  async addDomain() {
    const input = document.getElementById('domain-input');
    const domain = input.value.trim();
    
    if (!domain) {
      alert('请输入域名');
      return;
    }
    
    if (this.webList.includes(domain)) {
      alert('域名已存在');
      return;
    }
    
    this.webList.push(domain);
    await this.saveData();
    
    input.value = '';
    this.updateUI();
  }

  /**
   * 从白名单移除域名
   */
  async removeDomain(domain) {
    const index = this.webList.indexOf(domain);
    if (index > -1) {
      this.webList.splice(index, 1);
      await this.saveData();
      this.updateUI();
    }
  }

  /**
   * 渲染域名列表
   */
  renderDomainList() {
    const listElement = document.getElementById('domain-list');
    
    if (this.webList.length === 0) {
      listElement.innerHTML = '<li class="empty-state">暂无域名，请添加需要拦截的域名前缀</li>';
      return;
    }
    
    listElement.innerHTML = this.webList.map(domain => `
      <li class="domain-item">
        <span class="domain-text">${domain}</span>
        <button class="remove-btn" data-action="remove-domain" data-domain="${domain}">删除</button>
      </li>
    `).join('');
    
    // 绑定删除按钮事件
    document.querySelectorAll('[data-action="remove-domain"]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const domain = e.target.dataset.domain;
        this.removeDomain(domain);
      });
    });
  }

  /**
   * 清空请求列表
   */
  async clearRequests() {
    if (confirm('确定要清空所有请求记录吗？')) {
      this.requestList = [];
      await this.saveData();
      this.updateUI();
    }
  }

  /**
   * 刷新请求列表
   */
  async refreshRequests() {
    await this.loadData();
    this.updateUI();
  }

  /**
   * 过滤请求列表
   */
  filterRequests() {
    this.renderRequestList();
  }

  /**
   * 渲染请求列表
   */
  renderRequestList() {
    const tableElement = document.getElementById('request-table');
    const filterText = document.getElementById('request-filter').value.toLowerCase();
    const methodFilter = document.getElementById('method-filter').value;
    
    let filteredRequests = this.requestList.filter(request => {
      const matchText = !filterText || 
        request.url.toLowerCase().includes(filterText) ||
        request.method.toLowerCase().includes(filterText);
      const matchMethod = !methodFilter || request.method === methodFilter;
      return matchText && matchMethod;
    });
    
    if (filteredRequests.length === 0) {
      tableElement.innerHTML = '<div class="empty-state">暂无请求记录</div>';
      return;
    }
    
    const tableHTML = `
      <table class="table">
        <thead>
          <tr>
            <th>方法</th>
            <th>URL</th>
            <th>状态码</th>
            <th>时间</th>
            <th>Mock</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          ${filteredRequests.map(request => `
            <tr>
              <td><span class="method-badge method-${request.method.toLowerCase()}">${request.method}</span></td>
              <td class="url-cell" title="${request.url}">${request.url}</td>
              <td><span class="status-badge status-${Math.floor(request.responseCode/100)}xx">${request.responseCode}</span></td>
              <td>${new Date(request.timestamp).toLocaleTimeString()}</td>
              <td>${request.isMocked ? '✓' : '-'}</td>
              <td>
                <button class="action-btn view-btn" data-action="view-request" data-request-id="${request.id}">查看</button>
                <button class="action-btn mock-btn" data-action="create-mock-from-request" data-request-id="${request.id}">Mock</button>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
    
    tableElement.innerHTML = tableHTML;
    
    // 绑定请求操作按钮事件
    tableElement.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const action = e.target.dataset.action;
        const requestId = e.target.dataset.requestId;
        
        switch(action) {
          case 'view-request':
            this.viewRequestDetails(requestId);
            break;
          case 'create-mock-from-request':
            this.createMockFromRequestId(requestId);
            break;
        }
      });
    });
  }

  /**
   * 查看请求详情
   */
  viewRequestDetails(requestId) {
    const request = this.requestList.find(r => r.id === requestId);
    if (!request) return;
    
    const detailsHTML = `
      <div class="request-detail">
        <h4>基本信息</h4>
        <p><strong>方法:</strong> ${request.method}</p>
        <p><strong>URL:</strong> ${request.url}</p>
        <p><strong>状态码:</strong> ${request.responseCode}</p>
        <p><strong>时间:</strong> ${new Date(request.timestamp).toLocaleString()}</p>
        <p><strong>是否Mock:</strong> ${request.isMocked ? '是' : '否'}</p>
        
        <h4>请求参数</h4>
        <pre>${request.requestParams || '无'}</pre>
        
        <h4>请求头</h4>
        <pre>${JSON.stringify(request.requestHeaders || {}, null, 2)}</pre>
        
        <h4>请求体</h4>
        <pre>${request.requestBody || '无'}</pre>
        
        <h4>响应体</h4>
        <pre>${request.responseBody || '无'}</pre>
      </div>
    `;
    
    document.getElementById('request-details').innerHTML = detailsHTML;
    document.getElementById('request-modal').classList.add('show');
    
    // 保存当前请求ID用于创建Mock
    this.currentRequestId = requestId;
  }

  /**
   * 隐藏请求详情弹窗
   */
  hideRequestModal() {
    document.getElementById('request-modal').classList.remove('show');
    this.currentRequestId = null;
  }

  /**
   * 从请求创建Mock规则
   */
  createMockFromRequest() {
    if (!this.currentRequestId) return;
    
    const request = this.requestList.find(r => r.id === this.currentRequestId);
    if (!request) return;
    
    this.hideRequestModal();
    this.showMockModal({
      url: new URL(request.url).pathname,
      statusCode: request.responseCode,
      mockJson: request.responseBody
    });
  }

  /**
   * 从请求ID创建Mock规则
   */
  createMockFromRequestId(requestId) {
    const request = this.requestList.find(r => r.id === requestId);
    if (!request) return;
    
    this.showMockModal({
      url: new URL(request.url).pathname,
      statusCode: request.responseCode,
      mockJson: request.responseBody
    });
  }

  /**
   * 显示Mock编辑弹窗
   */
  showMockModal(data = null) {
    const modal = document.getElementById('mock-modal');
    const title = document.getElementById('modal-title');
    
    if (data) {
      title.textContent = data.id ? '编辑Mock规则' : '新增Mock规则';
      document.getElementById('mock-url').value = data.url || '';
      document.getElementById('mock-status').value = data.statusCode || 200;
      document.getElementById('mock-delay').value = data.delay || 0;
      document.getElementById('mock-json').value = typeof data.mockJson === 'string' ? 
        data.mockJson : JSON.stringify(data.mockJson || {}, null, 2);
      document.getElementById('mock-enabled').checked = data.disabled !== true;
      this.currentMockId = data.id || null;
    } else {
      title.textContent = '新增Mock规则';
      document.getElementById('mock-url').value = '';
      document.getElementById('mock-status').value = 200;
      document.getElementById('mock-delay').value = 0;
      document.getElementById('mock-json').value = '';
      document.getElementById('mock-enabled').checked = true;
      this.currentMockId = null;
    }
    
    modal.classList.add('show');
  }

  /**
   * 隐藏Mock编辑弹窗
   */
  hideMockModal() {
    document.getElementById('mock-modal').classList.remove('show');
    this.currentMockId = null;
  }

  /**
   * 保存Mock规则
   */
  async saveMock() {
    const url = document.getElementById('mock-url').value.trim();
    const statusCode = parseInt(document.getElementById('mock-status').value);
    const delay = parseInt(document.getElementById('mock-delay').value);
    const jsonText = document.getElementById('mock-json').value.trim();
    const enabled = document.getElementById('mock-enabled').checked;
    
    if (!url) {
      alert('请输入URL');
      return;
    }
    
    let mockJson;
    try {
      mockJson = jsonText ? JSON.parse(jsonText) : {};
    } catch (error) {
      alert('Mock数据格式错误，请输入有效的JSON');
      return;
    }
    
    const mockRule = {
      id: this.currentMockId || this.generateId(),
      originUrl: url,
      mockJson: mockJson,
      disabled: !enabled,
      statusCode: statusCode,
      delay: delay,
      createTime: Date.now()
    };
    
    if (this.currentMockId) {
      // 编辑现有规则
      const index = this.mockList.findIndex(m => m.id === this.currentMockId);
      if (index > -1) {
        this.mockList[index] = mockRule;
      }
    } else {
      // 添加新规则
      this.mockList.push(mockRule);
    }
    
    await this.saveData();
    this.hideMockModal();
    this.updateUI();
  }

  /**
   * 删除Mock规则
   */
  async deleteMock(mockId) {
    if (confirm('确定要删除这个Mock规则吗？')) {
      const index = this.mockList.findIndex(m => m.id === mockId);
      if (index > -1) {
        this.mockList.splice(index, 1);
        await this.saveData();
        this.updateUI();
      }
    }
  }

  /**
   * 切换Mock规则状态
   */
  async toggleMock(mockId) {
    const mock = this.mockList.find(m => m.id === mockId);
    if (mock) {
      mock.disabled = !mock.disabled;
      await this.saveData();
      this.updateUI();
    }
  }

  /**
   * 渲染Mock列表
   */
  renderMockList() {
    const tableElement = document.getElementById('mock-table');
    
    if (this.mockList.length === 0) {
      tableElement.innerHTML = '<div class="empty-state">暂无Mock规则，点击"新增Mock"创建规则</div>';
      return;
    }
    
    const tableHTML = `
      <table class="table">
        <thead>
          <tr>
            <th>URL</th>
            <th>状态码</th>
            <th>延迟</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          ${this.mockList.map(mock => `
            <tr>
              <td class="url-cell" title="${mock.originUrl}">${mock.originUrl}</td>
              <td><span class="status-badge status-${Math.floor(mock.statusCode/100)}xx">${mock.statusCode}</span></td>
              <td>${mock.delay}ms</td>
              <td>
                <label class="switch">
                  <input type="checkbox" ${mock.disabled ? '' : 'checked'} data-action="toggle-mock" data-mock-id="${mock.id}">
                  <span class="slider"></span>
                </label>
              </td>
              <td>${new Date(mock.createTime).toLocaleDateString()}</td>
              <td>
                <button class="action-btn edit-btn" data-action="edit-mock" data-mock-id="${mock.id}">编辑</button>
                <button class="action-btn delete-btn" data-action="delete-mock" data-mock-id="${mock.id}">删除</button>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
    
    tableElement.innerHTML = tableHTML;
    
    // 绑定Mock操作按钮和开关事件
    tableElement.querySelectorAll('[data-action]').forEach(element => {
      if (element.type === 'checkbox') {
        element.addEventListener('change', (e) => {
          const mockId = e.target.dataset.mockId;
          this.toggleMock(mockId);
        });
      } else {
        element.addEventListener('click', (e) => {
          const action = e.target.dataset.action;
          const mockId = e.target.dataset.mockId;
          
          switch(action) {
            case 'edit-mock':
              this.editMock(mockId);
              break;
            case 'delete-mock':
              this.deleteMock(mockId);
              break;
          }
        });
      }
    });
  }

  /**
   * 编辑Mock规则
   */
  editMock(mockId) {
    const mock = this.mockList.find(m => m.id === mockId);
    if (mock) {
      this.showMockModal({
        id: mock.id,
        url: mock.originUrl,
        statusCode: mock.statusCode,
        delay: mock.delay,
        mockJson: mock.mockJson,
        disabled: mock.disabled
      });
    }
  }

  /**
   * 生成唯一ID
   */
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  /**
   * 打开配置管理页面
   */
  openConfigPage() {
    chrome.runtime.openOptionsPage();
  }

  /**
   * 切换Debugger模式
   */
  async toggleDebugger() {
    try {
      // 获取当前活动标签页
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      
      if (!tab) {
        alert('无法获取当前标签页');
        return;
      }

      const action = this.debuggerStatus.enabled ? 'STOP_DEBUGGING' : 'START_DEBUGGING';
      
      // 发送消息给background script
      const response = await chrome.runtime.sendMessage({
        action: action,
        tabId: tab.id
      });
      
      if (response && response.success) {
        this.debuggerStatus.enabled = !this.debuggerStatus.enabled;
        if (this.debuggerStatus.enabled) {
          this.debuggerStatus.attachedTabs.push(tab.id);
        } else {
          this.debuggerStatus.attachedTabs = this.debuggerStatus.attachedTabs.filter(id => id !== tab.id);
        }
        this.updateDebuggerUI();
        
        const statusText = this.debuggerStatus.enabled ? '已启动' : '已停止';
        console.log(`Debugger模式${statusText}`);
      } else {
        alert('Debugger操作失败，请检查权限设置');
      }
    } catch (error) {
      console.error('切换Debugger模式失败:', error);
      alert('操作失败: ' + error.message);
    }
  }

  /**
   * 刷新Debugger状态
   */
  async refreshDebuggerStatus() {
    try {
      const response = await chrome.runtime.sendMessage({
        action: 'GET_DEBUGGER_STATUS'
      });
      
      if (response) {
        this.debuggerStatus.attachedTabs = response.attachedTabs || [];
        this.debuggerStatus.pendingRequests = response.pendingRequests || 0;
        this.debuggerStatus.enabled = this.debuggerStatus.attachedTabs.length > 0;
        this.updateDebuggerUI();
      }
    } catch (error) {
      console.error('获取Debugger状态失败:', error);
    }
  }

  /**
   * 更新Debugger UI状态
   */
  updateDebuggerUI() {
    const toggleBtn = document.getElementById('debugger-toggle-btn');
    const statusBtn = document.getElementById('debugger-status-btn');
    
    if (toggleBtn) {
      toggleBtn.textContent = this.debuggerStatus.enabled ? '停止Debugger' : '启动Debugger';
      toggleBtn.className = `btn ${this.debuggerStatus.enabled ? 'btn-danger' : 'btn-primary'}`;
    }
    
    if (statusBtn) {
      const statusText = `状态: ${this.debuggerStatus.enabled ? '运行中' : '已停止'} | 附加标签: ${this.debuggerStatus.attachedTabs.length} | 待处理: ${this.debuggerStatus.pendingRequests}`;
      statusBtn.textContent = statusText;
    }
  }
}

// 初始化弹窗
const popup = new NetworkInterceptorPopup();

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'NEW_REQUEST') {
    popup.requestList.unshift(message.request);
    popup.saveData();
    popup.updateUI();
  }
});